package com.ruoyi.function.service.impl;


import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.function.service.FileUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${ruoyi.profile}")
    private String uploadPath;

    @Value("${ruoyi.apiUrl}")
    private String apiUrl; // API基础URL配置

    @Override
    public String uploadFile(MultipartFile file, String type) throws Exception {
        // 1. 文件校验
        checkFile(file);
        
        // 2. 生成文件存储目录
        String datePath = DateUtils.datePath(); // 按年月日生成目录
        String directory = uploadPath + "/" + type + "/" + datePath;
        
        // 3. 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = getExtension(originalFilename);
        String fileName = generateUniqueFileName(extension);
        
        // 4. 创建目录
        File dest = new File(directory);
        if (!dest.exists()) {
            if (!dest.mkdirs()) {
                throw new ServiceException("创建目录失败");
            }
        }
        
        // 5. 保存文件
        try {
            File saveFile = new File(directory, fileName);
            file.transferTo(saveFile);
            
            // 6. 返回完整的HTTP URL路径
            return apiUrl + "/profile/" + type + "/" + datePath + "/" + fileName;
        } catch (IOException e) {
            throw new ServiceException("文件保存失败");
        }
    }
    
    /**
     * 生成唯一文件名
     */
    private String generateUniqueFileName(String extension) {
        // UUID + 时间戳 + 3位随机数，保证文件名唯一性
        return UUID.randomUUID().toString().replace("-", "") 
               + "_" + System.currentTimeMillis() 
               + "_" + (int)((Math.random() * 900) + 100) 
               + "." + extension;
    }
    
    /**
     * 校验文件
     */
    private void checkFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("文件不能为空");
        }
        
        // 校验文件大小
        if (file.getSize() > 10 * 1024 * 1024) { // 10MB
            throw new ServiceException("文件大小不能超过10MB");
        }
        
        // 校验文件类型
        String extension = getExtension(file.getOriginalFilename());
        if (!isAllowedExtension(extension)) {
            throw new ServiceException("只能上传jpg/png/jpeg格式的图片");
        }
    }
    
    /**
     * 判断是否是允许的文件类型
     */
    private boolean isAllowedExtension(String extension) {
        String[] allowedExtension = {"jpg", "jpeg", "png"};
        for (String ext : allowedExtension) {
            if (ext.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件扩展名
     */
    private String getExtension(String filename) {
        if (filename == null) {
            return null;
        }
        int index = filename.lastIndexOf(".");
        if (index == -1) {
            return "";
        }
        return filename.substring(index + 1);
    }
} 